const {
	config
} = require('../../common/config.js')
const ServerError = require('../../common/error')

const db = uniCloud.database();
const dbCmd = db.command

async function orderList(page = 0, limit = 10) {
	page = parseInt(page)
	limit = parseInt(limit)
	let {
		affectedDocs,
		data
	} = await db.collection('order').get();
	return {
		errCode: 0,
		data: data,
		errMsg: "order列表"
	}
}

async function searchOrder() {
	let httpInfo = this.getHttpInfo()
	let {
		ordersn,
		tel,
		beginTime,
		endTime
	} = JSON.parse(httpInfo.body)
	let getRes;
	if (ordersn) {
		getRes = await db.collection('order').doc(ordersn).get();
	} else if (tel) {
		getRes = await db.collection('order').where({
			'address.tel': tel
		}).get();
	} else if (beginTime) {
		let bt = (new Date(beginTime)).getTime()
		let et = (new Date(endTime)).getTime()
		getRes = await db.collection('order').where({
			"create_time": dbCmd.gt(bt).and(dbCmd.lt(et))
		}).get();
	} else {
		throw new ServerError("请输入查询条件", 1404);
	}
	return {
		errCode: 0,
		data: getRes.data,
		errMsg: "order搜索"
	}

}

async function setSendNo() {
	let httpInfo = this.getHttpInfo()
	let {
		_id,
		sendno
	} = JSON.parse(httpInfo.body)
	let {
		affectedDocs,
		data
	} = await db.collection('order').doc(_id).get();
	if (data.length > 0 && data[0].wait_status == 2) {
		let {
			affectedDocs,
			updated
		} = await db.collection('order').doc(_id).update({
			wait_status: 3,
			sendno: sendno
		})
		if (updated > 0) {
			return {
				errCode: 0,
				data: {
					updated
				},
				errMsg: "物流添加成功"
			}
		} else {
			throw new ServerError(`设置失败`, 3012)
		}
	} else {
		throw new ServerError("没有该订单信息", 3031)
	}

}
module.exports = {
	orderList,
	searchOrder,
	setSendNo
}
